<?php

namespace App\Http\Controllers\Admin;

use App\Models\TurnActivity;
use App\Models\TurnActivityResource;
use App\Models\Manage;
use App\Models\TurnActivityGift;
use App\Models\TurnActivityUserUsePrizeRecord;
use Illuminate\Support\Facades\DB;

/**
 * 在线抽奖活动类
 */
class TurnActivityController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\TurnActivity();
        $this->validate = new  \App\Validate\TurnActivityValidate();
    }



    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * 
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $is_play = $this->request->is_play;

        $res = $this->model->lists(null, $keywords, $is_play, $start_time, $end_time, $create_start_time, $create_end_time, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['rule'] = $val['rule_type'] == 1 ? str_replace('&nbsp;', '', strip_tags($val['rule'])) : $val['rule'];
            $res['data'][$key]['status'] = $this->model->getActListStatus($val);

            $res['data'][$key]['execute_day_array'] = $this->model->getActExecuteDay($val); //获取活动执行天数

            $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['manage_id']);

            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            $res['data'][$key]['is_have_gift'] = TurnActivityGift::isHaveGift($val['id']) === true ? true : false; //是否配置礼物
            $res['data'][$key]['is_have_color'] = true;
            $res['data'][$key]['is_have_img'] = true;
            $turnActivityResource = new TurnActivityResource();
            $color_info = $turnActivityResource->detail($val['id']);
            if (empty($color_info)) {
                $res['data'][$key]['is_have_color'] = false;
                $res['data'][$key]['is_have_img'] = false;
            } else {
                if (empty($color_info['resource_path'])) {
                    $res['data'][$key]['is_have_img'] = false;
                }
                if (empty($color_info['theme_color'])) {
                    $res['data'][$key]['is_have_color'] = false;
                }
            }
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 活动id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        $real_info_array = $this->model->getAnswerActivityApplyParam();
        $res->real_info_value = $this->getRealInfoArray($res->real_info, $real_info_array, 'value');
        $res->real_info_value = join("|", $res->real_info_value);

        $res->execute_day_array = $this->model->getActExecuteDay($res); //获取活动执行天数

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /** 
     * 新增
     * @param title string 活动名称  
     * @param img string 活动封面   
     * @param node int   执行时间类型    1 单次  2 每周   3 每月   
     * @param execute_day int 执行时间设置   如果是每周，1代表星期一，2代表星期2，多个逗号拼接，如果是每月，1代表 1号，2代表 2号，多个逗号拼接
     * @param real_info string  选填 如果不是阅享用户则必填   填写信息  如果是阅享用户，则无效    1、姓名  2、电话   3、身份证号码  4、读者证   多个  | 连接
     * @param number int 次数，根据 vote_way执行方式， 总形式，则表示总执行次数，每日模式，则是每日次数    
     * @param round_number int 每轮几次    设置前端抽奖后（或抽几次后），重置界面
     * @param vote_way int 活动执行方式    1 总数量形式   2 每日执行形式
     * @param share_number int 分享获取答题次数，每日几次  
     * @param rule_type int 规则方式   1 内容   2外链
     * @param rule  规则内容     rule_type  为1 这里是编辑器内容   2 这里是链接
     * @param start_time datetime 活动开始时间
     * @param end_time datetime 活动结束时间
     * @param turn_start_time datetime 开始抽奖时间
     * @param turn_end_time datetime 结束抽奖时间
     * @param invite_code string 邀请码  6位
     * @param share_title string 分享标题
     * @param share_img string 分享图片
     * @param is_show_address string 前端界面是否填写地址 1 需要  2 不需要
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "该活动名称已存在");
        }
        if ($this->request->invite_code && strlen($this->request->invite_code) != 6) {
            return $this->returnApi(202, "活动邀请码必须是6位");
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_turn_activity.png',
                'node' => $this->request->node,
                'execute_day' => $this->request->execute_day,
                'is_ushare' => !empty(config('other.is_ushare')) ? config('other.is_ushare') : 2,
                'real_info' => empty(config('other.is_ushare')) || config('other.is_ushare') == 2 ? $this->request->real_info : null,
                'vote_way' => $this->request->vote_way,
                'number' => $this->request->number,
                'round_number' => $this->request->round_number,
                'share_number' => $this->request->share_number ? $this->request->share_number : 0,
                'rule_type' => $this->request->rule_type,
                'rule' => $this->request->rule,

                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'turn_start_time' => $this->request->turn_start_time,
                'turn_end_time' => $this->request->turn_end_time,

                'manage_id' => $this->request->manage_id,
                'invite_code' => $this->request->invite_code,
                'share_title' => $this->request->share_title,
                'share_img' => $this->request->share_img,
                'is_show_address' => $this->request->is_show_address ? $this->request->is_show_address : 1,
            ];
            $this->model->add($data);
            //生成存放资源路径
            $activityResourceModel = new TurnActivityResource();
            $activityResourceModel->createImgStoreDir($this->model->id);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /** 
     * 修改
     * @param id string 活动id 
     * @param title string 活动名称  
     * @param img string 活动封面   
     * @param node int   执行时间类型    1 单次  2 每周   3 每月   
     * @param execute_day int 执行时间设置   如果是每周，1代表星期一，2代表星期2，多个逗号拼接，如果是每月，1代表 1号，2代表 2号，多个逗号拼接
     * @param real_info string  选填 如果不是阅享用户则必填   填写信息  如果是阅享用户，则无效    1、姓名  2、电话   3、身份证号码  4、读者证   多个  | 连接
     * @param number int 次数，根据 vote_way执行方式， 总形式，则表示总执行次数，每日模式，则是每日次数    
     * @param round_number int 每轮几次    设置前端抽奖后（或抽几次后），重置界面
     * @param vote_way int 活动执行方式    1 总数量形式   2 每日执行形式
     * @param share_number int 分享获取答题次数，每日几次  
     * @param rule_type int 规则方式   1 内容   2外链
     * @param rule  规则内容     rule_type  为1 这里是编辑器内容   2 这里是链接
     * @param start_time datetime 活动开始时间
     * @param end_time datetime 活动结束时间
     * @param turn_start_time datetime 开始抽奖时间
     * @param turn_end_time datetime 结束抽奖的时间
     * @param invite_code string 邀请码  6位
     * @param share_title string 分享标题
     * @param share_img string 分享图片
     * @param is_show_address string 前端界面是否填写地址 1 需要  2 不需要
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }

        //判断是否可以修改是否循环模式
        if ($res->node != $this->request->node || $res->execute_day != $this->request->execute_day || $res->number != $this->request->number || $res->vote_way != $this->request->vote_way) {
            //判断是否有人答题
            $turnActivityUserUsePrizeRecordModel = new TurnActivityUserUsePrizeRecord();
            $isDraw = $turnActivityUserUsePrizeRecordModel->isDraw($id);
            if ($isDraw) {
                return $this->returnApi(202, "此活动已有用户参与，不能修改；抽奖时间类型、抽奖时间设置、抽奖次数、抽奖执行方式");
            }
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该活动名称已存在");
        }
        if ($this->request->invite_code && strlen($this->request->invite_code) != 6) {
            return $this->returnApi(202, "活动邀请码必须是6位");
        }

        $old_img = $res->img;

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $this->request->id,
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_turn_activity.png',
                'node' => $this->request->node,
                'execute_day' => $this->request->execute_day,
                'is_ushare' => !empty(config('other.is_ushare')) ? config('other.is_ushare') : 2,
                'real_info' => empty(config('other.is_ushare')) || config('other.is_ushare') == 2 ? $this->request->real_info : null,
                'vote_way' => $this->request->vote_way,
                'number' => $this->request->number,
                'round_number' => $this->request->round_number,
                'share_number' => $this->request->share_number,
                'rule_type' => $this->request->rule_type,
                'rule' => $this->request->rule,

                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'turn_start_time' => $this->request->turn_start_time,
                'turn_end_time' => $this->request->turn_end_time,
                'invite_code' => $this->request->invite_code,
                'share_title' => $this->request->share_title,
                'share_img' => $this->request->share_img,
                'is_show_address' => $this->request->is_show_address ? $this->request->is_show_address : 1,
            ];
            $this->model->change($data);

            //删除旧资源
            if ($old_img != $this->request->img && $old_img != 'default/default_turn_activity.png') {
                $this->deleteFile($old_img);
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "修改失败");
        }
    }

    /**
     * 删除
     * @param id int 活动id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, null, null);
        if (empty($res)) {
            return $this->returnApi(201, "参数传递错误");
        }
        //判断是否有人答题
        $turnActivityUserUsePrizeRecordModel = new TurnActivityUserUsePrizeRecord();
        $isDraw = $turnActivityUserUsePrizeRecordModel->isDraw($this->request->id);

        if ($isDraw) {
            return $this->returnApi(202, "此活动已有用户参与，不允许删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }



    /**
     * 撤销 和发布
     * @param id int 活动id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断是否符合发布的条件
        if ($this->request->is_play == 1) {
            $is_can_play = $this->model->isCanPlay($this->request->id);
            if ($is_can_play !== true) {
                return $this->returnApi(202, $is_can_play);
            }
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 邀请码修改
     * @param id int 活动id
     * @param invite_code int 邀请码  6 位纯数字
     */
    public function invitCodeChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('invite_code_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }
        DB::beginTransaction();
        try {
            $res->invite_code = $this->request->invite_code;
            $res->save();

            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 设置答题总规则
     * @param act_id 活动id
     * @param answer_rule 答题规则   1、专属题和公共题 混合  2、优先回答专属题 
     */
    // public function set_answer_rule()
    // {
    //     //增加验证场景进行验证
    //     if (!$this->validate->scene('get_answer_rule')->check($this->request->all())) {
    //         return $this->returnApi(201,  $this->validate->getError());
    //     }
    //     $res = $this->model->find($this->request->id);
    //     if (empty($res)) {
    //         return $this->returnApi(202, '参数传递错误');
    //     }

    //     $res->answer_rule = $this->request->answer_rule;
    //     $result = $res->save();
    //     if ($result) {
    //         return $this->returnApi(200, '设置成功');
    //     }
    //     return $this->returnApi(200, '设置失败');
    // }

    /**
     * 复制活动
     * @param act_id 活动id
     * @param password  管理员密码
     */
    public function copyData()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('copy_data')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断管理员密码是否正确
        $is_success = Manage::passwordIsSuccess($this->request->manage_id, $this->request->password);

        if (!$is_success) {
            return $this->returnApi(202, '密码输入错误');
        }
        $res = $this->model->where('id', $this->request->act_id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();
        unset($res['id']);
        unset($res['browse_num']);
        unset($res['create_time']);
        unset($res['change_time']);

        DB::beginTransaction();
        try {
            $res['manage_id'] = $this->request->manage_id;
            $res['is_play'] = 2; //默认未发布
            $this->model->add($res);

            DB::commit();
            return $this->returnApi(200, "复制成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "复制失败");
        }
    }
}
